//
//  InstituIntroduceViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/9/11.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "InstituIntroduceViewController.h"
#import "InstituteModel.h"
#import "InstituIntroListCell.h"
#import "InstittuIntroBottomCell.h"
#import "AddressNavgationViewController.h"
#import "AddressInstituteNearbyViewController.h"
#import <MapKit/MapKit.h>
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Search/BMKPoiSearch.h>
#import <BaiduMapAPI_Map/BMKAnnotation.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import "InstituteDetailIntCell.h"
@interface InstituIntroduceViewController ()<UITableViewDelegate,UITableViewDataSource,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate>

@property(nonatomic,strong)UITableView *tablview;
@property(nonatomic,strong)NSArray *titlesArray;
@property(nonatomic,strong)NSArray *detailTitlesArray;
@property(nonatomic,strong)NSArray *imageSarray;

@property (nonatomic,strong) BMKMapView *mapView;//地图视图
@property(nonatomic,strong)BMKLocationService *service;
@property(nonatomic,strong)BMKPoiSearch *poiSearch;
@property (nonatomic,strong) NSMutableArray *mdataArray;
@end

@implementation InstituIntroduceViewController

- (NSMutableArray *)mdataArray {
    if (!_mdataArray) {
        _mdataArray = [NSMutableArray array];
        
    }
    return _mdataArray;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createtablview];
    NSLog(@"%@",self.dataArray);
    // Do any additional setup after loading the view.
}
-(void)createtablview{
    self.tablview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - (64 + 40 + scaleTopAndBottom(200))) style:UITableViewStylePlain];
    [self.view addSubview:self.tablview];
    self.tablview.delegate = self;
    self.tablview.dataSource = self;
    [self.tablview registerClass:[InstituIntroListCell class] forCellReuseIdentifier:@"InstituIntroListCell"];
        [self.tablview registerClass:[InstittuIntroBottomCell class] forCellReuseIdentifier:@"InstittuIntroBottomCell"];
    [self.tablview registerClass:[InstituteDetailIntCell class] forCellReuseIdentifier:@"InstituteDetailIntCell"];
        self.tablview.estimatedRowHeight = 200;
    [self.tablview reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titlesArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    InstituIntroListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InstituIntroListCell"];
        cell.titleLabel.text = self.titlesArray[indexPath.row];
        cell.detaLabel.text = self.detailTitlesArray[indexPath.row];
    if (indexPath.row == 4 ) {
        InstituteDetailIntCell *cells = [tableView dequeueReusableCellWithIdentifier:@"InstituteDetailIntCell"];
        cells.titleLabel.text = self.detailTitlesArray[indexPath.row];
        cells.imgView.image = [UIImage imageNamed:self.imageSarray[indexPath.row - 4]];
        return cells;
    }
    if (indexPath.row == 5 ) {
        InstituteDetailIntCell *cells = [tableView dequeueReusableCellWithIdentifier:@"InstituteDetailIntCell"];
        cells.titleLabel.text = self.detailTitlesArray[indexPath.row];
        cells.imgView.image = [UIImage imageNamed:self.imageSarray[indexPath.row - 4]];
        UILabel *subLabel = [[UILabel alloc] init];
        subLabel.text = @"快速查询";
        subLabel.textColor = [UIColor lightGrayColor];
        subLabel.font = [UIFont systemFontOfSize:13];
        [cells.contentView addSubview:subLabel];
        [subLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cells.contentView.mas_centerY);
            make.height.mas_equalTo(15);
            make.right.equalTo(cells.contentView.mas_right).offset(scaleLeftAndRight(10));
            make.width.mas_equalTo(scaleLeftAndRight(60));
            
        }];
        return cells;
    }
    if (indexPath.row == 6 ) {
        InstituteDetailIntCell *cells = [tableView dequeueReusableCellWithIdentifier:@"InstituteDetailIntCell"];
        cells.titleLabel.text = self.detailTitlesArray[indexPath.row];
        cells.imgView.image = [UIImage imageNamed:self.imageSarray[indexPath.row - 4]];
        return cells;
    }
        if (indexPath.row == 7) {
            InstittuIntroBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InstittuIntroBottomCell"];
            cell.titleLabel.text = self.titlesArray[indexPath.row];
            cell.titleLabel.font = [UIFont systemFontOfSize:13];
            [self createBMKMapViewinView:cell.backView];
            return cell;
        }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 7) {
        return scaleTopAndBottom(210);
    }
    return scaleTopAndBottom(50);
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 5) {
        NSString *phoneNumber = self.detailTitlesArray[indexPath.row];
        NSString *MessageStr = [NSString stringWithFormat:@"%@%@",@"tel://",phoneNumber];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:MessageStr]];
    }
    if (indexPath.row == 6) {
        NSString *emailStr = self.detailTitlesArray[indexPath.row];
        NSString *emailSt = [NSString stringWithFormat:@"mailto://%@",emailStr];
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:emailSt]];
    }
    if (indexPath.row == 4) {
        self.valueBlock(self.detailTitlesArray[indexPath.row],self.detailTitlesArray[0]);
    }
    if (indexPath.row == 7) {
        self.modelBlock();
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSArray *)titlesArray{
    if (_titlesArray == nil) {
        _titlesArray = @[@"名称",@"成立时间",@"企业规模(人)",@"机构类型",@"机构地址",@"联系电话",@"邮箱地址",@"查看附近机构"];
    }
    return _titlesArray;
}
-(NSArray *)detailTitlesArray{
    if (_detailTitlesArray == nil) {
        InstituteModel *model = self.dataArray[0];
        NSString *areas = [NSString stringWithFormat:@"%@%@%@",model.province,model.city,model.area];
        NSString *timeStr = [self timestampSwitchTime:[model.foundTime integerValue]  andFormatter:@"YYYY-MM-dd"];
        NSString *cataStr = @"";
        for (NSInteger i = 0; i < model.institutionCategorys.count; i++) {
            NSString *str = [NSString stringWithFormat:@" %@",model.institutionCategorys[i].name];
            cataStr = [cataStr stringByAppendingString:str];
        }
        NSLog(@"%@",cataStr);
        _detailTitlesArray = @[model.name,timeStr,[self accodingBtnChooseBackInfor:model.number],cataStr,areas,model.phoneNumber,model.email,model.Description];
    }
    return _detailTitlesArray;
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
/**
 根据按钮上边的人数返回具体的值
 
 */
-(NSString *)accodingBtnChooseBackInfor:(NSString *)peopleCount{
    
    if ([peopleCount isEqual:@"0"]) {
        return [NSString stringWithFormat:@"100人以下"];
    }else if ([peopleCount isEqual:@"1"]){
        return [NSString stringWithFormat:@"100-500人"];
    }else if ([peopleCount isEqual:@"2"]){
        return [NSString stringWithFormat:@"500-1000人"];
    }else if ([peopleCount isEqual:@"3"]){
        return [NSString stringWithFormat:@"1000-5000人"];
    }else if ([peopleCount isEqual:@"4"]){
        return [NSString stringWithFormat:@"5000-10000人"];
    }else{
        return [NSString stringWithFormat:@"10000人以上"];
    }
    
}
-(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp/1000];
    
    NSLog(@"1296035591 = %@",confromTimesp);
    
    
    
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    
    
    //NSLog(@"&&&&&&&confromTimespStr = : %@",confromTimespStr);
    
    
    
    return confromTimespStr;
    
}
#pragma mark -设置底部的地图的代理
-(void)createBMKMapViewinView:(UIView *)view{
    sleep(0.7);
    self.mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, scaleLeftAndRight(10), WIDTH - 2 *scaleLeftAndRight(10), scaleTopAndBottom(160))];
    self.mapView.delegate = self;
    [self.mapView setMapType:BMKMapTypeStandard];
    self.mapView.trafficEnabled = YES;
    self.mapView.showMapPoi = YES;
    self.mapView.zoomLevel = 21;
    self.mapView.rotateEnabled = NO;
    self.mapView.scrollEnabled = YES;
    self.mapView.showMapScaleBar = YES;
    [view addSubview:self.mapView];
    self.service = [[BMKLocationService alloc] init];
    self.service.delegate = self;
    [self.service startUserLocationService];
}
#pragma makr -地图定位的代理方法
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    self.mapView.showsUserLocation = YES;
    [self.mapView updateLocationData:userLocation];
    self.mapView.centerCoordinate = userLocation.location.coordinate;
    self.mapView.zoomLevel = 18;
    //初始化搜索
    self.poiSearch =[[BMKPoiSearch alloc] init];
    self.poiSearch.delegate = self;
    
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc] init];
    option.pageIndex = 0;
    option.pageCapacity = 50;
    option.radius = 1000;
    option.location = userLocation.location.coordinate;
    option.keyword = @"儿童机构";
    //    根据中心点，半径和检索词发起周边搜索
    BOOL flag = [self.poiSearch poiSearchNearBy:option];
    if (flag) {
        NSLog(@"搜索成功");
        [self.service stopUserLocationService];
        
    }else{
        NSLog(@"搜索失败");
    }
}
#pragma mark -搜索的代理方法
-(void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    //若搜索成功
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        //POI信息类 //poi列表
        for (BMKPoiInfo *info in poiResult.poiInfoList) { [self.dataArray addObject:info];
            //初始化一个点的注释 //只有三个属性
            BMKPointAnnotation *annotoation = [[BMKPointAnnotation alloc] init];
            //坐标
            annotoation.coordinate = info.pt;
            //title
            annotoation.title = info.name;
            NSLog(@"这是你想要的名字%@",annotoation.title);
            //子标题
            annotoation.subtitle = info.address;
            //将标注添加到地图上
            [self.mapView addAnnotation:annotoation];
            NSLog(@"他么的");
        } }
    
}
-(void)onGetPoiDetailResult:(BMKPoiSearch *)searcher result:(BMKPoiDetailResult *)poiDetailResult errorCode:(BMKSearchErrorCode)errorCode{
    NSLog(@"%@",poiDetailResult.name);
}

#pragma mark -地图的代理方法

-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        //根据注视点创建标注
        BMKPinAnnotationView *newAnnotion = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotion.pinColor = BMKPinAnnotationColorRed;
        newAnnotion.animatesDrop = YES;
        NSLog(@"走了么");
        return newAnnotion;
    }
    return nil;
}
-(void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
//    for (NSInteger i = 0; i < views.count; i++) {
//        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *) [views objectAtIndex:i];
//        [mapView selectAnnotation:annotationView.annotation animated:YES];
//    }
    
//    BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *) [views objectAtIndex:0];
//    [mapView selectAnnotation:annotationView.annotation animated:YES];

    
    
//    BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *) [views objectAtIndex:0];
//    [mapView selectAnnotation:annotationView.annotation animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil;
    self.service.delegate = nil;
    self.poiSearch.delegate = nil;
}
-(void)dealloc{
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil;
    self.service.delegate = nil;
    self.poiSearch.delegate = nil;
}
/**
 当选中一个annotionview时调用此接口
 
 */
-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    BMKPoiDetailSearchOption *option = [[BMKPoiDetailSearchOption alloc] init];
    BMKPoiInfo *infor = self.mdataArray.firstObject;
    option.poiUid = infor.uid;
    
    BOOL flag= [self.poiSearch poiDetailSearch:option];
    if (flag) {
        NSLog(@"检索成功");
    }else{
        NSLog(@"检索失败");
    }
}
-(NSArray *)imageSarray{
    if (_imageSarray == nil) {
        _imageSarray = @[@"introLocal",@"introphone",@"introEmail"];
    }
    return _imageSarray;
}


///**
// 获取机构数据
// */
//-(void)getDataInformation{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    NSString *url = ServerIp@"/institutionApp/institutionDetailAll";
//    NSDictionary *param = @{@"Id":self.instituId};
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
